﻿using CRM_S.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Security;

namespace CRM_S.Controllers
{
    public class LoginController : ApiController
    {
        public IHttpActionResult Login([FromBody] User user)
        {
            using (cremEntities db = new cremEntities())
            {
                var list = db.Users.SingleOrDefault(p => p.loginName == user.loginName);
                if (list != null)
                {
                    if (list.isLockout == 0)
                    {
                        return Json(new { code = -1, msg = "用户已经被锁定" });
                    }
                    else
                    {
                        if (user.password == list.password)
                        {
                            //FormsAuthentication.SetAuthCookie(user.LoginName, true);
                            list.lockTime = null;
                            list.errorCount = 0;
                            db.SaveChanges();
                            return Json(new { code = 0, msg = "登录成功!", token = list.uid });
                        }
                        if (list.errorCount > 2)
                        {
                            list.isLockout = 0;
                            db.SaveChanges();
                            list.lockTime = DateTime.Now;
                            db.SaveChanges();
                            return Json(new { success = -3, message = "你密码错误的次数大于三次，账号已被锁定,请联系管理员解除禁用" });
                        }
                        else
                        {
                            list.errorCount += 1;
                            db.SaveChanges();
                            return Json(new { code = -2, msg = "密码错误" });
                        }

                    }
                   
                }
                else
                {
                    return Json(new { code = -1, msg = "用户不存在" });
                }
            }
        }
        [HttpGet]
        public IHttpActionResult GetAllProducts()
        {
            //using (crmDBEntities db = new crmDBEntities())
            //{
            //    var data = db.Users.Select(p => new {
            //        Id = p.uid,
            //        LoginName = p.loginName
            //    }).ToList();
            //    return Json(new { data = data });
            //}
            return Json(new { data = "sdfsdf" });
        }

    }
}
